package main

import (
	"fmt"
	"math/rand"
	"time"
	"sync"
)

var rwMutex sync.RWMutex
var value int

func writeNum(idx int) {
	for {
		// 生成随机数
		num := rand.Intn(1000)
		rwMutex.Lock() // 以写模式加锁
		value = num
		fmt.Printf("%dth 写go程，写入：%d\n", idx, num)
		time.Sleep(time.Millisecond * 300) // 放大实验现象
		rwMutex.Unlock()
	}

}
func readNum(idx int) {
	for {
		rwMutex.RLock() // 以读模式加锁
		num := value
		fmt.Printf("----%dth 读 go程，读出：%d\n", idx, num)
		rwMutex.RUnlock() // 以读模式解锁
		time.Sleep(time.Second)
	}

}
func main() {
	rand.Seed(time.Now().UnixNano())
	for i := 0; i < 5; i++ {
		go readNum(i + 1)
	}
	for i := 0; i < 5; i++ {
		go writeNum(i + 1)
	}

	for {
		;
	}
}
